# -*- coding: utf-8 -*-
import json
import re
import time
from config import etc
from controls import data_user_base_mysql, data_topic_title_mysql
from utils import log
from utils.reg_expressions import phone_regex
from utils.session_base import ApiHost
from utils.session_mc import BaseHandler
from utils.verify_code import check_verify_code, VERIFY_TYPE_REGISTER
from utils.wx_utils.weixin_jsticket import weixin_noncestr, weixin_appid, get_signature


class WebSigninHandler(BaseHandler):
    def get(self):
        if self.current_user:
            if not self.current_user.get('phone'):
                self.redirect('/web/bind/phone')

            log.i('redirect to topic list')
            self.redirect('/web/topic/list')
            return

        log.i('web Signin')
        self.render('web/signin.html')


class WebBindPhoneHandler(BaseHandler):
    def get(self):
        log.i('web bind phone')
        self.render('web/bind_phone.html')

    @ApiHost
    def post(self):
        phone = self.ss_params['phone']
        passwd = self.ss_params['passwd']
        verify = self.ss_params['verify']
        log.i('phone=%s , passwd=%s , verify=%s , ssid=%s' % (phone, passwd, verify, self.ssid))
        if not phone:
            log.w('empty phone')
            res = {'idx': self.ss_idx, 'ret': 2, 'msg': '手机号不能为空', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        phone = phone.strip()
        rephone = re.compile(phone_regex)
        if not rephone.match(phone):
            log.w('phone verify failed')
            res = {'idx': self.ss_idx, 'ret': 3, 'msg': '手机号格式有误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if not check_verify_code(phone, VERIFY_TYPE_REGISTER, verify):
            log.i('verify error')
            res = {'idx': self.ss_idx, 'ret': 6, 'msg': '验证码错误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if data_user_base_mysql.get_user_base_by_phone(phone):
            log.i('phone has been used')
            res = {'idx': self.ss_idx, 'ret': 4, 'msg': '该手机号已被注册', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        userid = self.ss_user['userid']
        if not userid:
            log.e('userid fetching error')
            res = {'idx': self.ss_idx, 'ret': 5, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if not data_user_base_mysql\
                .update_user_phone_and_password_by_userid(userid, phone, passwd):
            log.e('user base create error')
            res = {'idx': self.ss_idx, 'ret': 6, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        log.i('new user base/info created: userid=%s, phone=%s , passwd=%s' % (userid, phone, passwd))

        self.ss_user['phone'] = phone
        self.ss_store.set(self.ssid, self.ss_user)

        log.i('login now : userid=%s , ssid=%s' % (self.ss_user['userid'], self.ssid))
        res = {
            'idx': self.ss_idx,
            'ret': 0,
            'msg': '绑定成功',
            'res': {
            }
        }
        self.write(json.dumps(res))
        self.finish()
        return


class WebTopicListHandler(BaseHandler):
    def get(self):
        log.i('web topic list')
        return self.render('web/topic_list.html')


class WebNoteListHandler(BaseHandler):
    def get(self):
        if self.current_user:
            auth = 1
        else:
            auth = 0

        log.i('web note list')

        time_now = int(time.time())
        render_settings = {
            'noncestr': weixin_noncestr,
            'timestamp': time_now,
            'appid': weixin_appid,
            'signature': get_signature(weixin_noncestr, time_now,
                                       self.request.full_url())
        }

        render_settings.update({
            'auth': auth,
        })
        return self.render('web/note_list.html', **render_settings)


class WebNotePostHandler(BaseHandler):
    def get(self):
        log.i('web note list')
        return self.render('web/note_post.html')


class WebFindPwdHandler(BaseHandler):
    def get(self):
        if self.current_user:
            log.i('redirect to topic list')
            self.redirect('/web/topic/list')
            return

        log.i("web find pwd")
        return self.render('web/find_pwd.html')


class TopicTopNoteListHandler(BaseHandler):
    def get(self, *args, **kwargs):
        topicid = data_topic_title_mysql.get_newest_topicid()
        return self.redirect('/web/note/list?topicid=' + str(topicid) )